package com.bnlr.lrparking.appui.appoint;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.constant.LrConstant;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.appui.stall.StallDealDetailActivity;
import com.bnlr.lrparking.appui.login.VerificaActivity;
import com.bnlr.lrparking.base.BaseFragment;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.model.BaseArrayBean;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.appui.appoint.adapter.AppointAdapter;
import com.bnlr.lrparking.appui.appoint.bean.AppointBean;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.lrparking.widget.refresh.RefreshHolderUtil;
import com.bnlr.lrparking.widget.refresh.XRefreshLayout;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class AppointFragment extends BaseFragment {
    private Unbinder unbinder;
    private static final String TAG = "AppointFragment";
    private int positionIndex;
    @BindView(R.id.x_refresh)
    XRefreshLayout xRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.ll_hint)
    LinearLayout noData;
    @BindView(R.id.iv_hint)
    ImageView ivEmpty;
    @BindView(R.id.tv_hint_tips)
    TextView tvEmpty;
    private AppointAdapter adapter;
    private List<AppointBean.DataBean> dataList = new ArrayList<>();
    private int type;
    public static AppointFragment newInstance(int position) {
        Bundle args = new Bundle();
        AppointFragment fragment = new AppointFragment();
        args.putInt(TAG,position);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_appoint, container, false);
        unbinder = ButterKnife.bind(this,view);
        positionIndex = getArguments().getInt(TAG);
        switch (positionIndex) {
            case 0:
                type = LrConstant.SELL;
                break;
            case 1:
                type = LrConstant.RENT;
                break;

            default:
                break;
        }
        initView();
        return view;
    }

    private void initView() {
        ivEmpty.setImageResource(R.drawable.no_appoint);
        tvEmpty.setText("暂无预约信息哟");
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        xRefreshLayout.setRefreshViewHolder(RefreshHolderUtil.getRefreshHolder(getActivity()));
        xRefreshLayout.setDelegate(new XRefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(XRefreshLayout refreshLayout) {
                getAppointList();
            }
            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(XRefreshLayout refreshLayout) {
                return false;
            }
        });
        adapter = new AppointAdapter(dataList);
        recyclerView.setAdapter(adapter);
        xRefreshLayout.beginRefreshing();
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getActivity(), StallDealDetailActivity.class);
                intent.putExtra("stall_id", dataList.get(position).getSpaceId());
                startActivity(intent);
            }
        });
        adapter.setAppointHandlerListener(new AppointAdapter.AppointHandlerListener() {
            @Override
            public void onCancel(View view, final int position, final AppointBean.DataBean item, boolean isCancel) {
                CarCommon carCommon = new CarCommon();
                carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                    @Override
                    public void setSure() {
                        delAppoint(position,item.getId());
                    }
                });
                if (isCancel) {
                    carCommon.CommonDialog(getActivity(),"确定要取消此条预约信息吗？","提示");
                } else {
                    carCommon.CommonDialog(getActivity(),"确定要删除此条预约信息吗？","提示");
                }

            }


        });

    }

    /**
     * 取消或删除预约
     * @param position
     */
    private void delAppoint(final int position, int id) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.NEW_IP, LrConstant.POST);
            mRequest.add("action", "CancelUserWantedSpace");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("id",id);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomHttpListener<BaseArrayBean>(getActivity(), true, BaseArrayBean.class) {
                        @Override
                        public void doWork(BaseArrayBean data, String code) {
                            if (TextUtils.equals("1", code)) {
                                dataList.remove(position);
                                adapter.setNewData(dataList);
                                if (dataList.size() == 0) {
                                    noData.setVisibility(View.VISIBLE);
                                }
                            } else {
                                ToastUtils.showShort(data.getMsg());
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            if (xRefreshLayout != null) {
                                xRefreshLayout.endRefreshing();
                            }
                            try {
                                if (!TextUtils.equals("1", code) && (obj.getString("msg").contains("用户已在其他手机上登录")||
                                        obj.getString("msg").contains("请重新登录"))) {
                                    final CarCommon carCommon = new CarCommon();
                                    carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                                        @Override
                                        public void setSure() {
                                            Intent intent = new Intent(getActivity(), VerificaActivity.class);
                                            getActivity().startActivity(intent);
                                        }
                                    });
                                    carCommon.ReminderDialog(getActivity(), "登录信息已过期，是否重新登录？","下线通知","立即登录");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, false);
        } catch (Exception e) {
        }
    }

    private void getAppointList() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.NEW_IP, LrConstant.POST);
            mRequest.add("action", "QueryMyWantSpace");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("isWantLook",1);
            mRequest.add("type",type);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomHttpListener<AppointBean>(getActivity(), true, AppointBean.class) {
                        @Override
                        public void doWork(AppointBean data, String code) {
                            if (TextUtils.equals("1", code)) {
                                if (adapter != null) {
                                    if (data != null && data.getData().size() != 0) {
                                        noData.setVisibility(View.GONE);
                                        dataList.clear();
                                        dataList.addAll(data.getData());
                                        adapter.setNewData(data.getData());
                                    } else {
                                        if (dataList.size() == 0) {
                                            noData.setVisibility(View.VISIBLE);
                                        }
                                    }
                                } else {
                                    ToastUtils.showShort(data.getMsg() + "");
                                }
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            if (xRefreshLayout != null) {
                                xRefreshLayout.endRefreshing();
                            }
                            try {
                                if (!TextUtils.equals("1", code) && (obj.getString("msg").contains("用户已在其他手机上登录")||
                                        obj.getString("msg").contains("请重新登录"))) {
                                    final CarCommon carCommon = new CarCommon();
                                    carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                                        @Override
                                        public void setSure() {
                                            Intent intent = new Intent(getActivity(), VerificaActivity.class);
                                            getActivity().startActivity(intent);
                                        }
                                    });
                                    carCommon.ReminderDialog(getActivity(), "登录信息已过期，是否重新登录？","下线通知","立即登录");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, false);
        } catch (Exception e) {
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
